package com.vincce.sport.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.http.client.fluent.Request;
import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.vincce.sport.core.entity.DateViewSession;
import com.vincce.sport.core.task.ScoreTask;
import com.vincce.sport.core.utils.CheckUtil;
import com.vincce.sport.core.utils.JsonUtil;
import com.vincce.sport.core.utils.RedisUtil;
import com.vincce.sport.core.weixin.HttpUtil;
import com.vincce.sport.core.weixin.WeixinTask;
import com.vincce.sport.entity.CompetitionGroup;
import com.vincce.sport.entity.CompetitionSeason;
import com.vincce.sport.entity.CompetitionTeam;
import com.vincce.sport.entity.DateView;
import com.vincce.sport.entity.GroupTaskEntity;
import com.vincce.sport.entity.MatchTaskEntity;
import com.vincce.sport.entity.Page;
import com.vincce.sport.entity.PlayerDataTask;
import com.vincce.sport.entity.SchoolRankView;
import com.vincce.sport.entity.ScoreTaskEntity;
import com.vincce.sport.entity.TeamDataTask;
import com.vincce.sport.entity.TeamDate;
import com.vincce.sport.mapper.CompetitionGroupMapper;
import com.vincce.sport.mapper.CompetitionSeasonMapper;
import com.vincce.sport.mapper.CompetitionTeamMapper;
import com.vincce.sport.mapper.DateViewMapper;
import com.vincce.sport.mapper.GroupTaskMapper;
import com.vincce.sport.mapper.MatchTaskMapper;
import com.vincce.sport.mapper.PlayerDataTaskMapper;
import com.vincce.sport.mapper.PreliminaryContestMapper;
import com.vincce.sport.mapper.SchoolRankViewMapper;
import com.vincce.sport.mapper.ScoreTaskMapper;
import com.vincce.sport.mapper.TeamDataTaskMapper;
import com.vincce.sport.mapper.TeamDateMapper;

@Controller
@RequestMapping("/task")
public class TimerTaskController extends BaseController{
	@Resource
	private SchoolRankViewMapper schoolRankViewMapper;
	@Resource
	private CompetitionSeasonMapper competitionSeasonMapper;
	@Resource
	private DateViewMapper dateViewMapper;
	@Resource
	private PlayerDataTaskMapper playerDataTaskMapper;
	static Logger logger = Logger.getLogger(ScoreTask.class);
	@Resource
	private TeamDateMapper teamDateMapper;
	@Resource
	private ScoreTaskMapper scoreTaskMapper;
	@Resource
	private PreliminaryContestMapper preliminaryContestMapper;
	@Resource
	private MatchTaskMapper matchTaskMapper;
	@Resource
	private CompetitionGroupMapper competitionGroupMapper;
	@Resource
	private CompetitionTeamMapper competitionTeamMapper;
	@Resource
	private GroupTaskMapper groupTaskMapper;
	@Resource
	private TeamDataTaskMapper teamDataTaskMapper;

	@RequestMapping("/start")
	@ResponseBody
	public String start(HttpServletRequest request){
		Map<String, Object> result = new HashMap<String, Object>();
		boolean flag = false;
		try {
			if(checkIp(request)){
				schoolTask();
				indexDataViewTask();
				weixinTask();
				playerDataTask();
				updateScore();
				preMatch();
				updateTeamGroupInfo();
				teamDataTask();
				flag = true;
			} else{
				result.put("flag", flag);
				result.put("message", "你的ip被禁止访问！");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		result.put("flag", flag);
		return JSON.toJSONString(result);
	}
	
	@RequestMapping("/timeTask")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
    public String timerTask(){
		String flag="数据初始化失败，请联系管理员或者<a href='/home.htm'>返回</a>主界面";
		try {
			schoolTask();
			indexDataViewTask();
			weixinTask();
			playerDataTask();
			updateScore();
			preMatch();
			updateTeamGroupInfo();
			teamDataTask();
			flag="数据初始化完毕，<a href='/home.htm'>返回</a>主界面";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			flag="数据初始化失败，请联系管理员或者<a href='/home.htm'>返回</a>主界面";
		}
		return flag;
	}
	@Transactional(rollbackFor = Exception.class)
    public String schoolTask(){
		Long flag=0l;
		List<SchoolRankView> dateViewList=new ArrayList<SchoolRankView>();
		SchoolRankView schoolRankView=new SchoolRankView();
		Map<String, Object> filter = new HashMap<String, Object>();	
		Page<CompetitionSeason> page=new Page<CompetitionSeason>();
		filter=new HashMap<String, Object>();	
	    filter.put("status", 1);
	    page.setLimit(1);
	    page.setFilter(filter);
	    page.setResult(competitionSeasonMapper.findCompetitionSeasonList(page));
	    Date date=new Date();
		if(page!=null && page.getResult().size()>0){
			Map<String, Object> map = new HashMap<String, Object>();	
			Long seasonId=page.getResult().get(0).getId();
			schoolRankView.setSeasonId(seasonId);
			dateViewList = schoolRankViewMapper.querySchoolRankView(schoolRankView);
			if(dateViewList!=null && dateViewList.size()>0){
				//删除之前的				
				map.put("seasonId", seasonId);
				schoolRankViewMapper.deleteBySeasonId(map);
				//插入
				for(SchoolRankView dateView:dateViewList){
					dateView.setSeasonId(dateView.getSeasonId());
					dateView.setZoneId(dateView.getZoneId());
					dateView.setMatchWon(dateView.getMatchWon());
					dateView.setMatchLost(dateView.getMatchLost());
					dateView.setPoints(dateView.getPoints());
					dateView.setWinning(dateView.getWinning());
					dateView.setScore(dateView.getScore());
					dateView.setSchoolId(dateView.getSchoolId());
					dateView.setUpdateTime(date);
					flag=schoolRankViewMapper.insertSchoolRankView(dateView);
				}
				
			}			
		}	
		return flag<=0?"false":"true";
	}
	
    @Transactional(rollbackFor = Exception.class)
    public String indexDataViewTask(){
		Long flag=0l;
		List<DateView> dateViewList=new ArrayList<DateView>();
		List<DateView> playerDateByTotalScoreList=new ArrayList<DateView>();
		List<DateView> playerDateByBackboardList=new ArrayList<DateView>();
		List<DateView> playerDateByAssistsAstsList=new ArrayList<DateView>();
		List<DateView> teamDateByBackboardList=new ArrayList<DateView>();
		List<DateView> teamDateByTotalScoreList=new ArrayList<DateView>();
		List<DateView> teamDateByHitList=new ArrayList<DateView>();
		Map<String, Object> filter = new HashMap<String, Object>();	
		Page<CompetitionSeason> page=new Page<CompetitionSeason>();
		filter=new HashMap<String, Object>();	
	    filter.put("status", 1);
	    page.setLimit(1);
	    page.setFilter(filter);
	    page.setResult(competitionSeasonMapper.findCompetitionSeasonList(page));
	    Date date=new Date();
		if(page!=null && page.getResult().size()>0){
			Map<String, Object> map = new HashMap<String, Object>();	
			Long seasonId=page.getResult().get(0).getId();
			map.put("seasonId", seasonId);
			//场均得分
			playerDateByTotalScoreList = dateViewMapper.queryPlayerDateByTotalScore(seasonId);
			if(playerDateByTotalScoreList!=null && playerDateByTotalScoreList.size()>0){
				//删除之前的				
				map.put("type", 1);
				dateViewMapper.deleteByType(map);
				//插入
				for(DateView dateView:playerDateByTotalScoreList){
					dateView.setSeasonId(seasonId);
					dateView.setType(1);
					dateView.setUpdateTime(date);
					flag=dateViewMapper.insertDateView(dateView);
				}
				
			}
			//场均篮板排名
			playerDateByBackboardList = dateViewMapper.queryPlayerDateByBackboard(seasonId);		
			if(playerDateByBackboardList!=null && playerDateByBackboardList.size()>0){
				//删除之前的
				map.put("type", 2);
				dateViewMapper.deleteByType(map);
				//插入
				for(DateView dateView:playerDateByBackboardList){
					dateView.setSeasonId(seasonId);
					dateView.setType(2);					
					dateView.setUpdateTime(date);
					flag=dateViewMapper.insertDateView(dateView);
				}
			}
			//场均助攻排名
			playerDateByAssistsAstsList = dateViewMapper.queryPlayerDateByAssistsAsts(seasonId);		
			if(playerDateByAssistsAstsList!=null && playerDateByAssistsAstsList.size()>0){
				//删除之前的
				map.put("type", 3);
				dateViewMapper.deleteByType(map);
				//插入
				for(DateView dateView:playerDateByAssistsAstsList){
					dateView.setSeasonId(seasonId);
					dateView.setType(3);					
					dateView.setUpdateTime(date);
					flag=dateViewMapper.insertDateView(dateView);
				}
			}
			//命中率排名-球队
			teamDateByHitList = dateViewMapper.queryTeamDateByHit(seasonId);		
			if(teamDateByHitList!=null && teamDateByHitList.size()>0){
				//删除之前的
				map.put("type", 4);
				dateViewMapper.deleteByType(map);
				//插入
				for(DateView dateView:teamDateByHitList){
					dateView.setSeasonId(seasonId);
					dateView.setType(4);					
					dateView.setUpdateTime(date);
					flag=dateViewMapper.insertDateView(dateView);
				}
			}
			//场均篮板排名-球队
			teamDateByBackboardList = dateViewMapper.queryTeamDateByBackboard(seasonId);		
			if(teamDateByBackboardList!=null && teamDateByBackboardList.size()>0){
				//删除之前的
				map.put("type", 5);
				dateViewMapper.deleteByType(map);
				//插入
				for(DateView dateView:teamDateByBackboardList){
					dateView.setSeasonId(seasonId);
					dateView.setType(5);					
					dateView.setUpdateTime(date);
					flag=dateViewMapper.insertDateView(dateView);
				}
			}
			//场均得分排名-球队
			teamDateByTotalScoreList = dateViewMapper.queryTeamDateByTotalScore(seasonId);	
			if(teamDateByTotalScoreList!=null && teamDateByTotalScoreList.size()>0){
				//删除之前的
				map.put("type", 6);
				dateViewMapper.deleteByType(map);
				//插入
				for(DateView dateView:teamDateByTotalScoreList){
					dateView.setSeasonId(seasonId);
					dateView.setType(6);					
					dateView.setUpdateTime(date);
					flag=dateViewMapper.insertDateView(dateView);
				}
			}
			//获取列表
			dateViewList=dateViewMapper.queryDateView(seasonId);
		}
		
		//放入redis	
		DateViewSession dateViewSession=new DateViewSession();
	    dateViewSession.setDateViewList(dateViewList);
		dateViewSession.setUpdateTime(date);
        RedisUtil.cacheAddUpdate(RedisUtil.DB_SPORT_DATEVIEW, "dateViewKey", dateViewSession, 86400);//超时时间为1天
        return flag<=0?"false":"true";
	}
	
    @Transactional(rollbackFor = Exception.class)
    public String weixinTask(){
		WeixinTask.GET_ACCESS_TOKEN = String.format(WeixinTask.GET_ACCESS_TOKEN, WeixinTask.APP_ID,WeixinTask.APP_SECRET);
		//获取ACCESS_TOKEN
		Request access_token_request = Request.Get(WeixinTask.URL_PREFIX+WeixinTask.GET_ACCESS_TOKEN);
		try {
			String response = HttpUtil.fetch(access_token_request);
			String json = new String(response.getBytes("iso-8859-1"), "utf-8");
			System.out.println(json);
			JSONObject object = JSONObject.parseObject(json);
			Map<String, Object> map = JsonUtil.jsonToMap(object);
			if(map.containsKey("access_token")){
				WeixinTask.TOKEN = map.get("access_token") == null ? "" : map.get("access_token").toString();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		//Request access_token_request = Request.Get(URL_PREFIX+GET_ACCESS_TOKEN);
		WeixinTask.GET_ATTENTION_TOTAL = String.format(WeixinTask.GET_ATTENTION_TOTAL, WeixinTask.TOKEN,"","%s");
		//获取总数
		Request attention_total_request = Request.Get(WeixinTask.URL_PREFIX + WeixinTask.GET_ATTENTION_TOTAL);
		try {
			String response = HttpUtil.fetch(attention_total_request);
			String json = new String(response.getBytes("iso-8859-1"), "utf-8");
			System.out.println(json);
			JSONObject object = JSONObject.parseObject(json);
			Map<String, Object> map = JsonUtil.jsonToMap(object);
			if(map.containsKey("total")){
				WeixinTask.TOTAL_ATTENTION = map.get("total") == null ? "0" : map.get("total").toString(); 
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return WeixinTask.TOTAL_ATTENTION;
	}
	
	@Transactional(rollbackFor = Exception.class)
	public void playerDataTask(){
		Map<String, Object> map =new HashMap<String, Object>();
		map.put("status", 1);
		List<PlayerDataTask> tasks =playerDataTaskMapper.queryByPlayerDataTaskList();
		
		if (tasks.size()>0 || tasks!=null) {
			//playerDataTaskMapper.truncatePlayerDataTask();//清空表数据
			List<CompetitionSeason> list = competitionSeasonMapper.findCompetitionSeason(map);
			CompetitionSeason season = list.get(0);
			if (season.getId()!= null) {
				playerDataTaskMapper.deleteBySeasonId(season.getId().intValue());
			}
			for (PlayerDataTask playerDataTask : tasks) {
				if (playerDataTask!=null) {
					playerDataTask.setUpdateTime(new Date());
					playerDataTaskMapper.insertPlayerDataTask(playerDataTask);
				}
			}
		}
		
	}
	
	/**
	 * 比分定时器
	 */
	@Transactional(rollbackFor = Exception.class)
	public void updateScore(){
		//获取主队数据
		List<ScoreTaskEntity> datalist = teamDateMapper.queryTeamDateBy4conditionAll();
		//List teamIdTwo = new ArrayList();
		//清空数据
		scoreTaskMapper.deleete();
		Map<String,Object> param = new HashMap<String, Object>();
		for (ScoreTaskEntity scoreTask : datalist) {
			//teamIdTwo.add(scoreTask.getTeamIdTwo());
			param.put("teamTwoId", scoreTask.getTeamIdTwo());
			param.put("contestId", scoreTask.getContestId());
			//查找对手得分信息
			ScoreTaskEntity opponent = teamDateMapper.queryTeamDataToTaskByOpponentId(param);
			if(opponent != null){
				scoreTask.setFirstSectionScoreTwo(opponent.getFirstSectionScore());
				scoreTask.setSecondSectionScoreTwo(opponent.getSecondSectionScore());
				scoreTask.setThirdSectionScoreTwo(opponent.getThirdSectionScore());
				scoreTask.setFourthSectionScoreTwo(opponent.getFourthSectionScore());
				scoreTask.setOverScoreTwo(opponent.getOverScore());
				scoreTask.setTotalScoreTwo(opponent.getTotalScore());
				scoreTask.setTeamNameTwo(opponent.getTeamName());
			}
				
			//插入临时比分表
			//判断该比赛比分已持久化
			//重新扫如数据
			scoreTaskMapper.insertScore(scoreTask);
			logger.info("插入***t_score_task**主队名称："+scoreTask.getTeamName()+"**contest_id:"+scoreTask.getContestId());
		}
		System.out.println("扫描结束");
	}

	/**
	 * 预赛赛程定时器
	 */
	@Transactional(rollbackFor=Exception.class)
	public void preMatch() throws Exception{
		//删除表中数据，重新插入扫到的数据
		matchTaskMapper.delete();
		//查詢所有的賽季
		Map<String,Object> map = new HashMap<String, Object>();
		List<CompetitionSeason> seasonList = competitionSeasonMapper.findCompetitionSeasonListAll();
		for (CompetitionSeason competitionSeason : seasonList) {
			//预赛比赛对阵情况
			map.put("seasonid", competitionSeason.getId());
			List<MatchTaskEntity> matchList = preliminaryContestMapper.queryPreliminaryTaskAllBySeasonId(map);
			for (MatchTaskEntity matchTaskEntity : matchList) {
				//保存至：t_match_task
				long count_insert = matchTaskMapper.insert(matchTaskEntity);
				logger.info("插入***t_match_task**pid："+matchTaskEntity.getPid());
			}
		}
	}
	
	/*
	 * 球队分组信息定时器
	 */
	@Transactional(rollbackFor=Exception.class)
	public void updateTeamGroupInfo() throws Exception{
		Map<String,Object> map = new HashMap<String, Object>();
		//map.clear();
		//List<CompetitionGroup> groupList = competitionGroupMapper.findCompetitionGroupList(map);
		groupTaskMapper.delete();
		//分组球队信息（小组中球队的序号、球队名字、球队ID）
		List<CompetitionTeam> teamInfoList = competitionTeamMapper.queryTeamInfo(map);
		for (CompetitionTeam competitionTeam : teamInfoList) {
			Map teamMap = new HashMap();
		//	teamMap.put("seasonId", seasonId);
			teamMap.put("teamId", competitionTeam.getTeamId());
			//计算球队比赛场数
			competitionTeam.setComCount(teamDateMapper.queryTeamDateByCount(teamMap));
			//胜场
			teamMap.put("winOrLose", "win");
			competitionTeam.setWinCount(teamDateMapper.queryTeamDateByCount(teamMap));
			//败场
			teamMap.put("winOrLose", "lose");
			competitionTeam.setLoseCount(teamDateMapper.queryTeamDateByCount(teamMap));
			//计算积分
			competitionTeam.setIntegration(competitionTeam.getWinCount()*2+competitionTeam.getLoseCount()*1);
			//保存入t_match_task
			//拼凑对象
			GroupTaskEntity groupTaskEntity = new GroupTaskEntity();
			groupTaskEntity.setGroupId(competitionTeam.getGroupId());
			groupTaskEntity.setTeamId(competitionTeam.getTeamId());
			groupTaskEntity.setNumber(competitionTeam.getNumber());
			groupTaskEntity.setTeamName(competitionTeam.getTeamName());
			groupTaskEntity.setSeasonId(competitionTeam.getSeasonId());
			groupTaskEntity.setComCount(competitionTeam.getComCount());
			groupTaskEntity.setWinCount(competitionTeam.getWinCount());
			groupTaskEntity.setLoseCount(competitionTeam.getLoseCount());
			groupTaskEntity.setIntegration(competitionTeam.getIntegration());
			groupTaskMapper.insert(groupTaskEntity);
			logger.info("******球队分组定时器插入数据，球队名字："+groupTaskEntity.getTeamName());
		}
	}
	
	@Transactional(rollbackFor = Exception.class)
	public void teamDataTask(){
		Map<String, Object> map =new HashMap<String, Object>();
		map.put("status", 1);
		List<TeamDataTask> dataTasks = teamDataTaskMapper.queryByTeamDataTaskList();
		if (dataTasks.size()>0 || dataTasks!=null ) {
			//teamDataTaskMapper.truncateTeamDataTask();
			List<CompetitionSeason> list = competitionSeasonMapper.findCompetitionSeason(map);
			CompetitionSeason season = list.get(0);
			if (season.getId()!= null) {
				teamDataTaskMapper.deleteBySeasonId(season.getId().intValue());
			}
			
			for (TeamDataTask teamDataTask : dataTasks) {
				if (teamDataTask!=null) {
					teamDataTask.setUpdateTime(new Date());
					teamDataTaskMapper.insertTeamDataTask(teamDataTask);
				}
			}
		}
		
	}
	
	/*
	 * 根据赛程ID即时更新比赛结果
	 */
	@RequestMapping("/updateScoreBygroupId")
	@ResponseBody
	public String updateScoreByTeamId(HttpServletRequest request){
//		String teamId = request.getParameter("teamId");//球队ID
		String groupID = request.getParameter("groupID");//对应赛程ID
		Map<String,Object> map = new HashMap<String, Object>();
//		map.put("teamId", teamId);
		map.put("contestId", groupID);
		Map<String,Object> resMap = new HashMap<String, Object>();
		//获取主队数据
		try {
			List<ScoreTaskEntity> datalist = teamDateMapper.queryTeamDateByTeamAndContest(map);
			//List teamIdTwo = new ArrayList();
			//清空数据
			//scoreTaskMapper.deleete();
			Map<String,Object> param = new HashMap<String, Object>();
			for (ScoreTaskEntity scoreTask : datalist) {
				//teamIdTwo.add(scoreTask.getTeamIdTwo());
				param.put("teamTwoId", scoreTask.getTeamIdTwo());
				param.put("contestId", scoreTask.getContestId());
				//查找对手得分信息
				ScoreTaskEntity opponent = teamDateMapper.queryTeamDataToTaskByOpponentId(param);
				scoreTask.setFirstSectionScoreTwo(opponent.getFirstSectionScore());
				scoreTask.setSecondSectionScoreTwo(opponent.getSecondSectionScore());
				scoreTask.setThirdSectionScoreTwo(opponent.getThirdSectionScore());
				scoreTask.setFourthSectionScoreTwo(opponent.getFourthSectionScore());
				scoreTask.setOverScoreTwo(opponent.getOverScore());
				scoreTask.setTotalScoreTwo(opponent.getTotalScore());
				scoreTask.setTeamNameTwo(opponent.getTeamName());
				//插入临时比分表
				//判断该比赛比分已持久化
				//重新扫如数据
				scoreTaskMapper.insertScore(scoreTask);
				//logger.info("插入***t_score_task**主队名称："+scoreTask.getTeamName()+"**contest_id:"+scoreTask.getContestId());
			}
			System.out.println("扫描结束");
			resMap.put("suc", true);
			resMap.put("groupID", groupID);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			resMap.put("suc", false);
			resMap.put("groupID", groupID);
			e.printStackTrace();
		}
		return JSON.toJSONString(resMap);
	}
}
